var Class        = require('./class'),
    Simulation   = require('./simulation'),
    Player       = require('./player'),
    Controller   = require('./controller'),
    socket       = io.connect(),
    player       = null
    game_room_id = location.href.split('/').slice(-1)[0];
    game_room_id = game_room_id.substring(0,1)

//console.log( io,'<- IO', socket, 'ROOM ->', game_room_id );

module.exports = GameClient = Class.extend({
    init: function(playerId, x, y, r, firstTick){
        var self = this;
        this.sim = new Simulation();
        //this.renderer = new Renderer(this.sim);
        
        this.width = 800;
        this.height = 600;
        
        this.lastTick = 0
        
        this.newPlayers = []
        this.deadPlayers = []
        this.seenDeadPlayers = {}
        
        this.controller = new Controller([{
                name: "left",
                keyCode: 37
            }, {
                name: "right",
                keyCode: 39
            }, {
                name: "up",
                keyCode: 38
            }, {
                name: "down",
                keyCode: 40
            },  
        ]);
        console.log('playerId:', playerId, ' color:', r)
        var player = this.player = new Player(this.sim,this.controller,x,y,0,
          r,0,0, playerId);
        this.sim.addEntity( this.player, this.player.id );
        var sim = this.sim;
        var newPlayers = this.newPlayers

        console.log('setup socket at ' + (new Date()))
        socket.on( 'connect', function () { console.log('send connect at ' + (new Date()))
            socket.emit( 'player-connected', {
                game_room_id : game_room_id,
                player_id    : player.id,
                color: player.r,
                x : player.x,
                y: player.y
            } );

            socket.on( 'server-tick', function (msg) {
              
                var now = new Date()
                var thisTick = now.getTime()
                if (typeof self.xxx == 'undefined') {
                  console.log('first server tick at ' + now)
                  self.xxx = 0 // max between ticks
//                  firstTick(self)
                } else {
                  var elapsed = thisTick - self.lastTick
                  if (elapsed > self.xxx) {
                    //console.log('new max between server-ticks:' + elapsed)
                    self.xxx = elapsed
                  }
                }
                self.lastTick = thisTick

                // msg contains array of player data
                var serverIds = {}
                msg.forEach(function(serverPlayer) {
                  var id = serverPlayer.id
                  serverIds[id] = true
                  var fplayer = sim.lookup(id);
                  if (!fplayer) {
                    // new player
                    fplayer = new Player(
                        sim, null, 0, 0, 0,1,0,0, serverPlayer.id
                    );
                    fplayer.id = serverPlayer.id;
                    sim.addEntity( fplayer, serverPlayer.id );
                    self.newPlayers.push(fplayer)
                    console.log(serverPlayer.x, ',', serverPlayer.y)
                  }
                  // update player
                  fplayer.x  = serverPlayer.x;
                  fplayer.y  = serverPlayer.y;
                  fplayer.z  = serverPlayer.z;
                  fplayer.vx = serverPlayer.vx;
                  fplayer.vy = serverPlayer.vy;
                  fplayer.vz = serverPlayer.vz;
                  fplayer.r = serverPlayer.r;
                  fplayer.g = serverPlayer.g;
                  fplayer.b = serverPlayer.b;
                })
                
                // sim.entities contains our live list
                // serverIds contains server's live ids'
                sim.entities.forEach(function(player) {
                  var id = player.id
                  if (!serverIds[id]) {
                    // this player died
                    if (!self.seenDeadPlayers[id]) {
                      // we did not know of this one
                      self.seenDeadPlayers[id] = true
                      self.deadPlayers.push(id)
                    }
                  }
                })
                
            } );
            
            }); // connect

        document.addEventListener( 'keydown', function(e){
            var action = self.controller.onInput(e);
            if (!action) return;

            socket.emit( 'player-input', {
                player_id    : player.id,
                game_room_id : game_room_id,
                action       : action
            } );

        }, false );

        document.addEventListener('keyup',function(e){
            var action = self.controller.onInput(e);
            if (!action) return;

            socket.emit( 'player-input', {
                player_id    : player.id,
                game_room_id : game_room_id,
                action       : action
            } );

        },false);
        
        firstTick(self)
    },
    start: function(){
        var self = this,
            lastLoopTime = (new Date()).getTime()/1000.0;
            
        this.intervalId = setInterval(function(){
            var newTime = (new Date()).getTime()/1000.0;
                self.timeElapsed = newTime-lastLoopTime;
                self.sim.update(self.timeElapsed);
                //self.renderer.render();
                lastLoopTime = newTime;
        },1000/60);
    },
    stop: function(){
        clearInterval(this.intervalId);
        this.intervalId = undefined;
    },
    setSpeed: function (vx, vy) {
      socket.emit( 'player-input', {
        player_id    : player.id,
        game_room_id : game_room_id,
        vx       : vx,
        vy: vy
      } );
    },
    getNewPlayers: function() {
      result = this.newPlayers
      if (result.length) this.newPlayers = []
      return result
    },
    getDeadPlayers: function() {
      result = this.deadPlayers
      if (result.length) this.deadPlayers = []
      return result
    }
});
